<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-upload-dragger
        :disabled="disabled"
        class="avatar-uploader"
        name="file"
        list-type="picture-card"
        :multiple="isMultiple"
        :action="uploadAction"
        :headers="headers"
        :data="{biz:bizPath}"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :show-upload-list="false"
        @change="handleChange"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="cloud-upload"/>
        </p>
        <p class="ant-upload-text">
          点击或拖动文件到此区域进行上传
        </p>
        <p class="ant-upload-hint">
          支持单个或批量上传。最多一次上传5张图片！
        </p>
      </a-upload-dragger>
    </div>
    <div id="content">
      <div v-viewer class="my-waterfall">
        <div class="image-content" v-for="(item,index) in dataSource" :key="index" @click="doCope(item.fileName)">
          <a-popover>
            <a slot="content" @click="deleteImg(item.id)">删除</a>
            <img src="#" v-lazy="item.url" :key="item.fileName"/>
          </a-popover>

        </div>
      </div>
    </div>
    <div class="pagination-di">
      <a-pagination
        :pageSizeOptions="pagination.pageSizeOptions"
        show-size-changer
        :showQuickJumper="pagination.showQuickJumper"
        :showSizeChanger="pagination.showSizeChanger"
        :default-current="1"
        :page-size.sync="pagination.pageSize"
        :total="pagination.total"
        @change="onChange"
        :show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
        @showSizeChange="onShowSizeChange"
      />
    </div>
  </a-card>
</template>

<script>
import AntsImageUpload from '@/components/ants/AntsImageUpload'
import { getToken } from '@/utils/auth'
import { getAction, getFileAccessHttpUrl, deleteAction } from '@/api/manage'
import { TableListMixin } from '@/mixins/TableListMixin'
import { filterObj } from '@/utils/util'
import store from '@/store'

export default {
  name: 'ImgUrlTool',
  components: {
    AntsImageUpload
  },
  data() {
    return {
      uploadAction: process.env.VUE_APP_BASE_API + '/antsFile/upload',
      headers: {},
      bizPath: 'imgUrl',
      fileList: [],
      isMultiple: true,
      number: 5,
      url: {
        list: '/antsFile/list',
        delete: '/antsFile/delete',
      },
      disabled: true,
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 50,
        pageSizeOptions: ['50', '100', '150'],
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 数据源 */
      dataSource: []
    }
  },
  created() {
    this.loadData()
    const token = getToken()
    this.headers = { 'Ants-Token': token }
  },
  mounted() {
    this.$notification['info']({
      message: '温馨提示',
      description:
        '点击图片预览大图并同时复制图片URL',
      duration: 0
    })
    // let _this = this
    // window.onscroll = function() {
    //   let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    //   let windowHeight = document.documentElement.clientHeight || document.body.clientHeight
    //   let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
    //   console.log('scrollTop + windowHeight', scrollTop + windowHeight)
    //   console.log('scrollHeight', scrollHeight)
    //   if (scrollTop + windowHeight == scrollHeight) {
    //     _this.pagination.current = _this.pagination.current++
    //     console.log('scrollTop + windowHeight == scrollHeight', scrollTop + windowHeight == scrollHeight)
    //     //滑动底部加载更多图片
    //     _this.loadData()
    //   }
    // }
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.pagination.current = 1
      }
      var params = this.getQueryParams()// 查询条件
      this.disabled = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.pagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.disabled = false
      })
    },
    getQueryParams() {
      const param = {}
      // 获取查询条件
      param.pageNo = this.pagination.current
      param.pageSize = this.pagination.pageSize
      return filterObj(param)
    },
    beforeUpload(file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    handleChange(info) {
      this.disabled = true
      let fileList = info.fileList
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.message
            }
            return file
          })
        } else {
          this.fileList = []
          this.disabled = false
          this.$message.error(`${info.file.name} 上传失败.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
      this.fileList = fileList
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.fileList = []
          this.disabled = false
          this.loadData()
        }
      }

    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    onShowSizeChange(current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.loadData()
    },
    onChange(pageNumber) {
      this.pagination.current = pageNumber
      this.loadData()
    },
    doCope(text) {
      let _this = this
      let url = this.getImgView(text)
      // 结果
      this.$copyText(url).then(function(e) {
        _this.$notification['success']({
          message: 'URL复制成功',
          description: url,
          placement: 'topLeft'
        })
      }, function(e) {
        _this.$notification['error']({
          message: 'URL复制失败',
          description: e,
          placement: 'topLeft'
        })
      })
    },
    deleteImg(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    }
  }
}


</script>

<style scoped>
.my-waterfall {
  display: flex;
  flex-wrap: wrap;
}

.image-content {
  margin: 5px;
  flex-grow: 1;
}

.my-waterfall img {
  display: block;
  min-width: 100%;
  height: 200px;
  object-fit: cover;

  cursor: pointer;
  transition: all 0.6s;
  border-radius: 10px;
}

.my-waterfall img:hover {
  transform: scale(1.05);
  transition: all .3s linear;
  cursor: pointer;
}

.pagination-div {
  margin-top: 20px;
  float: right;
}
</style>
